<template>
  <div class="login-wrap">
    <div v-if="isLogin" class="ms-login">
      <div class="ms-title">系统登录</div>
      <el-form
        v-if="!loginType"
        :validate-on-rule-change="false"
        :model="param"
        :rules="rules"
        ref="login"
        label-width="0px"
        class="ms-content"
      >
        <el-form-item prop="username">
          <el-input
            v-model="param.username"
            prefix-icon="el-icon-lx-people"
            placeholder="用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            prefix-icon="el-icon-lx-lock"
            placeholder="密码"
            v-model="param.password"
            @keyup.enter.native="submitForm()"
          >
          </el-input>
        </el-form-item>
        <div class="login-btn">
          <el-button type="primary" plain @click="toRegister">注册</el-button>
          <el-button type="primary" @click="submitForm()">登录</el-button>
        </div>
      </el-form>
    </div>

    <register v-if="!isLogin" @toLogin="isLogin = true"></register>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import { LOGIN, USERINFO } from "@/store";
import Register from "./Register";

export default {
  components: { register: Register },
  computed: {
    ...mapState(["token"]),
  },
  data() {
    return {
      isLogin: true,
      loginType: false,

      //发送验证码后的按钮loading
      loading: false,

      //验证码的form
      form: {
        phone: "",
        phone_access: "",
      },

      //验证码登录时的校验
      phoneCode: {
        phone: [
          { required: true, validator: this.checkPhone, trigger: "blur" },
        ],
        phone_access: [{ required: true, message: "请输入验证码" }],
      },

      //用户名密码登录时的form
      param: {
        username: "",
        password: "",
      },

      //用户名密码登录时的校验
      rules: {
        username: [{ required: true, message: "请输入用户名" }],
        password: [{ required: true, message: "请输入密码" }],
      },
    };
  },
  methods: {
    ...mapMutations(['resetState']),
    //用户名密码登录的方法
    submitForm() {
      this.$refs.login.validate((valid) => {
        if (valid) {
          this.$http
            .post("/auth/", this.param)
            .then((resp) => {
              this.$store.commit(LOGIN, resp.data.token);
              return this.$http.get("/myinfo/").then((info_resp) => {
                this.$store.commit(USERINFO, info_resp.data);
                this.$message({
                  message: "登录成功！",
                  type: "success",
                  duration: 1000,
                  center: true,
                });
                this.$router.push({ name: "dashboard" });
              });
            })
            .catch((err) => {
              if (err.response && err.response.status === 400) {
                console.error(err);
                this.$message.error({
                  message: "用户名或密码错误",
                  center: true,
                });
              } else {
                console.error(err);
              }
            });
        } else {
          this.$message.error("请输入账号和密码");
          console.log("error submit!!");
          return false;
        }
      });
    },
    //点击 '发送验证码' 按钮后的倒计时方法，调用countDown()方法即可，传入参数为倒计时时间，以秒为单位
    // 倒计时显示处理
    countDownText(s) {
      this.showtime = `${s}`;
    },
    // 倒计时 60秒 不需要很精准
    countDown(times) {
      this.loading = true;
      const self = this;
      // 时间间隔 1秒
      const interval = 1000;
      let count = 0;
      self.timeCounter = setTimeout(countDownStart, interval);

      function countDownStart() {
        if (self.timeCounter == null) {
          return false;
        }
        count++;
        self.countDownText(times - count + 1);
        if (count > times) {
          clearTimeout(self.timeCounter);
          self.showtime = null;
          this.loading = false;
        } else {
          self.timeCounter = setTimeout(countDownStart, interval);
        }
      }
    },

    //发送验证码的方法，传入参数为验证码form表单的ref，发送验证码之前需校验一次手机号
    sendCode() {
      this.form.phone_access = "";
      this.$refs.login.validateField("phone", (valid) => {
        if (!valid) {
          this.$http
            .post("/phoneauth/", { phone: this.form.phone })
            .then(() => {
              this.countDown(60);
              this.$message({
                message: "成功",
                type: "success",
              });
            })
            .catch((e) => {
              this.$message.error({
                message: e.response.statusText,
              });
            });
        } else {
          this.$message.error(valid);
        }
      });
    },

    //验证码登录的方法
    phoneCodeLogin() {
      this.$refs.phoneLogin.validate((valid) => {
        if (valid) {
          this.$http
            .post("/phonelogin/", this.form)
            .then((resp) => {
              this.$store.commit(LOGIN, resp.data.token);
              return this.$http.get("/myinfo/").then((info_resp) => {
                this.$store.commit(USERINFO, info_resp.data);
                this.$message({
                  message: "登录成功！",
                  type: "success",
                  duration: 1000,
                  center: true,
                });
                this.$router.push({ name: "dashboard" });
              });
            })
            .catch((e) => {
              if (err.response && err.response.status === 400) {
                this.$confirm("用户不存在，是否前去注册", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                })
                  .then(() => {
                    this.toRegister();
                  })
                  .catch(() => {
                    this.$message({
                      type: "info",
                      message: "已取消",
                    });
                  });
              }
            });
        }
      });
    },
    toRegister() {
      this.$refs.login && this.$refs.login.resetFields();
      this.isLogin = false;
    },
    checkPhone(rule, value, callback) {
      if (!value) {
        return callback(new Error("请输入手机号"));
      } else {
        const reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
        if (reg.test(value)) {
          callback();
        } else {
          return callback(new Error("请输入正确的手机号"));
        }
      }
    },
  },
  mounted() {
    if (this.token !== "") {
      this.$router.push("/home");
    } else {
      this.resetState();
    }
  },
};
</script>

<style scoped>
.login-wrap {
  /*position: relative;*/
  width: 100%;
  height: 100%;
  background-image: url(../../assets/img/login-bg.jpg);
  background-size: 100%;
}

body .el-scrollbar__wrap {
  overflow-x: hidden;
}

.ms-title {
  position: relative;
  width: 100%;
  line-height: 50px;
  text-align: center;
  font-size: 20px;
  color: #333;
  border-bottom: 1px solid #ddd;
}

.back-btn {
  position: absolute;
  left: 10px;
  top: 10px;
}

.ms-login {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 350px;
  margin: -190px 0 0 -175px;
  border-radius: 5px;
  background: rgba(255, 255, 255, 1);
  /*overflow: hidden;*/
}

.ms-content {
  padding: 30px 30px;
}

.login-btn {
  text-align: center;
}

.login-btn button {
  width: 48%;
  height: 36px;
  margin-bottom: 10px;
}

.login-tips {
  font-size: 12px;
  line-height: 30px;
  color: #fff;
}
</style>
